/*
 * Copyright 2010 Pierre-Yves Ricau
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.excilys.ptitwrap;

import java.util.List;

import org.restlet.engine.Engine;
import org.restlet.engine.converter.ConverterHelper;
import org.restlet.ext.jackson.JacksonConverter;
import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.content.Context;

/**
 * @author Pierre-Yves Ricau
 * 
 */
public class WrapResourceBuilder {

	public static WrapResource build(Context context) {

		List<ConverterHelper> converters = Engine.getInstance().getRegisteredConverters();

		if (converters.size() == 1) {
			converters.add(new PatchedJacksonConverter());
		}

		ClientResource clientResource = new ClientResource(context.getString(R.string.wrap_server) + "/rest/wraps");
		return clientResource.wrap(WrapResource.class);
	}

	private static class PatchedJacksonConverter extends JacksonConverter {

		@Override
		protected <T> JacksonRepresentation<T> create(Representation source, Class<T> objectClass) {
			return new PatchedJacksonRepresentation<T>(source, objectClass);
		}

	}

	private static class PatchedJacksonRepresentation<T> extends JacksonRepresentation<T> {

		private boolean	isVoidClass;

		public PatchedJacksonRepresentation(Representation representation, Class<T> objectClass) {
			super(representation, objectClass);
			isVoidClass = objectClass != null && objectClass.equals(void.class);
		}

		@Override
		public T getObject() {
			if (!isVoidClass) {
				return super.getObject();
			} else {
				return null;
			}
		}
	}

}
